<template>
  <div class="RoleManagement scroll-content">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item><a>角色管理</a></el-breadcrumb-item>
    </el-breadcrumb>
    <main>
      <div class="search-con">
        <el-form :model="searchInfo" label-width="90px">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="角色关键词" prop="keyWord">
                <el-input
                  v-model="searchInfo.keyWord"
                  placeholder="请输入编码、名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="创建人" prop="creator">
                <person-search v-model="searchInfo.creator" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="成员" prop="member">
                <person-search v-model="searchInfo.member" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" @click="getList">查询</el-button>
              <el-button @click="reset">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="table-con">
        <el-button type="primary" @click="add" v-if="ifCanAddRole"
          >新增角色</el-button
        >
        <el-table :data="tableData" border>
          <el-table-column
            label="角色编码"
            prop="code"
            align="center"
          ></el-table-column>
          <el-table-column
            label="角色名称"
            prop="name"
            align="center"
          ></el-table-column>
          <el-table-column
            label="创建日期"
            prop="create_time"
            width="160"
            align="center"
          ></el-table-column>
          <el-table-column label="创建人" prop="creator">
            <template slot-scope="scope">
              <show-person :personInfo="scope.row.creator" align="center" />
            </template>
          </el-table-column>
          <el-table-column
            label="成员"
            prop="partner"
            align="center"
            width="80"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="showDialog(scope.row)"
                v-if="scope.row.partner && scope.row.partner.length"
                >{{ scope.row.partner.length ?? 0 }}</el-button
              >
              <el-dialog
                :title="`角色成员(${scope.row.partner?.length}/${scope.row.number_ceil})`"
                :visible.sync="memberVisible"
                width="30%"
              >
                <el-table :data="showRow.partner">
                  <el-table-column label="人员名称">
                    <template slot-scope="scope">
                      <show-person :personInfo="scope.row" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="人员ID"
                    prop="employee_id"
                  ></el-table-column>
                </el-table>
              </el-dialog>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" align="center" width="80">
            <template slot-scope="scope">
              {{ scope.row.status ? "启用" : "停用" }}
            </template>
          </el-table-column>
          <el-table-column
            label="角色描述"
            prop="describe"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="operate(scope.row.status ? 'stop' : 'run', scope.row)"
                :disabled="scope.row.code === 'sysadmin'"
                v-if="ifCanChangeRoleStatus"
                >{{ scope.row.status ? "停用" : "启用" }}</el-button
              >
              <el-button
                v-for="item in buttons"
                type="text"
                :key="item.value"
                @click="operate(item.value, scope.row)"
                :disabled="
                  scope.row.code === 'sysadmin' && item.value !== 'edit'
                "
              >
                <span
                  v-if="
                    (item.value === 'edit' && ifCanEditRole) ||
                    (item.value === 'delete' && ifCanDeleteRole)
                  "
                  >{{ item.label }}</span
                >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="paginationInfo.current_page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="paginationInfo.page_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paginationInfo.total"
          background
        >
        </el-pagination>
      </div>
    </main>
    <el-dialog
      :title="`${memberType ? '新增' : '编辑'}角色`"
      :visible.sync="memberEAV"
      width="60%"
      custom-class="role-management-dialog"
      @closed="onBeforeClose"
    >
      <div class="dialog-content">
        <div class="left-content">
          <el-form
            :model="dialogModel"
            label-width="80px"
            :rules="rules"
            ref="memberRef"
          >
            <el-form-item label="角色编码" prop="code">
              <el-input
                v-model="dialogModel.code"
                placeholder="请输入角色名称"
                :disabled="!memberType"
              ></el-input>
            </el-form-item>
            <el-form-item label="角色名称" prop="name">
              <el-input
                v-model="dialogModel.name"
                placeholder="请输入角色编码"
                :disabled="!memberType && dialogModel.code === 'sysadmin'"
              ></el-input>
            </el-form-item>
            <el-form-item label="人数上限" prop="number_ceil">
              <el-input
                v-model="dialogModel.number_ceil"
                placeholder="请输入人数上限"
                maxlength="6"
                :disabled="!memberType && dialogModel.code === 'sysadmin'"
              ></el-input>
            </el-form-item>
            <el-form-item label="创建人" prop="creator">
              <el-input
                v-model="dialogModel.creator.employee_name"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="describe">
              <el-input
                v-model="dialogModel.describe"
                placeholder="请输入角色描述"
                type="textarea"
                :rows="4"
                resize="none"
                maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="right-content">
          <div class="content-top">
            <div class="top-left">
              <el-button type="primary" @click="addVisible = true"
                >添加</el-button
              >
              ({{ dialogModel.partner?.length ?? 0 }}/{{
                dialogModel.number_ceil ?? 0
              }})
            </div>
            <el-input
              v-model="topSearch"
              placeholder="请输入人员名称"
              suffix-icon="el-icon-search"
            ></el-input>
          </div>
          <el-table :data="dialogModel.partner">
            <el-table-column label="人员名称">
              <template slot-scope="scope">
                <show-person :personInfo="scope.row" />
              </template>
            </el-table-column>
            <el-table-column
              label="人员ID"
              prop="employee_id"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="del(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onBeforeClose">取 消</el-button>
        <el-button type="primary" @click="memberEAVConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="新增角色"
      :visible.sync="addVisible"
      width="30%"
      custom-class="role-management-add-dialog"
      @open="onOpen"
    >
      <el-form :model="addModel" ref="addRef">
        <el-form-item
          label="选择成员"
          prop="partner.employee_id"
          :rules="[{ required: true, message: '请选择成员' }]"
        >
          <person-search v-model="addModel.partner" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addModelConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import personSearch from "@/components/public/personSearch.vue";
import ShowPerson from "@/components/public/showPerson.vue";
import {
  addRole,
  deleteRole,
  editRole,
  getAllRole,
  runRole,
  stopRole,
} from "@/http/api";
import dayjs from "dayjs";
export default {
  components: { personSearch, ShowPerson },
  name: "RoleManagement",
  data() {
    return {
      searchInfo: {
        keyWord: "",
        creator: {},
        member: {},
      },
      tableData: [],
      buttons: [
        {
          label: "编辑",
          value: "edit",
        },
        {
          label: "删除",
          value: "delete",
        },
      ],
      memberVisible: false,
      memberType: 1,
      memberEAV: false,
      dialogModel: {
        code: "",
        name: "",
        number_ceil: "999999",
        creator: JSON.parse(localStorage.getItem("userInfo") || ""),
        describe: "",
        partner: [],
      },
      rules: {
        code: [
          {
            required: true,
            validator: (_, value, callback) => {
              if (value.trim().length === 0) {
                callback(new Error("不能为空"));
              } else {
                if (/^[a-z0-9A-Z]+$/.test(value)) {
                  callback();
                } else {
                  callback(new Error("正确格式:字母数字"));
                }
              }
            },
          },
        ],
        name: [{ required: true, message: "不能为空" }],
        number_ceil: [
          {
            required: true,
            validator: (_, value, callback) => {
              if ((value + "").trim().length === 0) {
                callback(new Error("不能为空"));
              }
              if (
                isNaN(Number(value)) ||
                Number(value) < 0 ||
                Math.floor(Number(value)) !== Number(value)
              ) {
                callback(new Error("请输入大于0的整数数值"));
              }
              callback();
            },
          },
        ],
        creator: [
          {
            required: true,
            type: "object",
            validate: (_, value, callback) => {
              if (value.employee_id) {
                callback();
              }
            },
          },
        ],
      },
      showRow: {},
      addVisible: false,
      addModel: {
        partner: {},
      },
      topSearch: "",
      paginationInfo: {
        current_page: 1,
        total: 0,
        page_size: 10,
      },
      ifCanAddRole: false,
      ifCanEditRole: false,
      ifCanDeleteRole: false,
      ifCanChangeRoleStatus: false,
      ifCanChangeEmployee: false,
    };
  },
  mounted() {
    this.getList();
    let authDetail = JSON.parse(localStorage.getItem("authority"));
    if (authDetail === "all") {
      this.ifCanAddRole = true;
      this.ifCanEditRole = true;
      this.ifCanDeleteRole = true;
      this.ifCanChangeRoleStatus = true;
      this.ifCanChangeEmployee = true;
    } else {
      this.ifCanAddRole = authDetail.includes("AddRole") ? true : false;
      this.ifCanEditRole = authDetail.includes("EditRole") ? true : false;
      this.ifCanDeleteRole = authDetail.includes("DeleteRole") ? true : false;
      this.ifCanChangeRoleStatus = authDetail.includes("ChangeRoleStatus")
        ? true
        : false;
      this.ifCanChangeEmployee = authDetail.includes("RoleEmployeeManage")
        ? true
        : false;
    }
  },
  methods: {
    reset() {
      this.searchInfo = {
        keyWord: "",
        creator: "",
        member: "",
      };
    },
    add() {
      this.memberType = 1;
      this.memberEAV = true;
    },
    async operate(type, row) {
      if (type !== "edit" && type !== "run") {
        this.$alert(`确定${type === "stop" ? "停用" : "删除"}`, {
          confirmButtonText: "确定",
          type: "warning",
          showCancelButton: true,
          callback: async (action) => {
            if (action === "confirm") {
              if (type === "stop") {
                let res = await stopRole(row.code);
                if (res.code === 20031) {
                  this.$message({
                    message: "停用成功",
                    type: "success",
                  });
                  this.getList();
                }
              } else {
                let res = await deleteRole(row.code);
                if (res.code === 20021) {
                  this.$message({
                    message: "删除成功",
                    type: "success",
                  });
                  this.getList();
                }
              }
            }
          },
        });
      } else if (type === "edit") {
        this.dialogModel = row;
        this.memberType = 0;
        this.memberEAV = true;
      } else {
        let res = await runRole(row.code);
        if (res.code === 20031) {
          this.$message({
            message: "启用成功",
            type: "success",
          });
          this.getList();
        }
      }
    },
    del(row) {
      this.dialogModel.partner = this.dialogModel.partner.filter(
        (item) => item.employee_id !== row.employee_id
      );
    },
    addModelConfirm() {
      this.$refs.addRef.validate((res) => {
        if (res) {
          if (
            this.dialogModel.partner == null ||
            this.dialogModel.partner.filter(
              (item) => item.employee_id === this.addModel.partner.employee_id
            ).length === 0
          ) {
            if (this.dialogModel.partner == null) {
              this.dialogModel.partner = [];
            }
            this.dialogModel.partner.push(this.addModel.partner);
          }
          this.addModel.partner = {};
          setTimeout(() => {
            this.addModel.partner = "";
            this.$refs.addRef.clearValidate();
          });
          this.addVisible = false;
        }
      });
    },
    memberEAVConfirm() {
      this.$refs.memberRef.validate(async (res, obj) => {
        if (res) {
          let res = {};
          if (this.memberType) {
            res = await addRole(this.dialogModel);
          } else {
            this.dialogModel.create_time = dayjs(this.dialogModel.create_time);
            res = await editRole(this.dialogModel);
          }
          if (res.code === 20011 || res.code === 20031) {
            this.onBeforeClose();
            this.$message({
              type: "success",
              message: res.code === 20011 ? "添加成功" : "修改成功",
            });
            this.getList();
          } else {
            this.$message({
              type: "error",
              message: res.msg,
            });
          }
        }
      });
    },
    onBeforeClose() {
      this.memberEAV = false;
      this.dialogModel = {
        code: "",
        name: "",
        number_ceil: "999999",
        creator: JSON.parse(localStorage.getItem("userInfo") || ""),
        describe: "",
        partner: [],
      };
      setTimeout(() => {
        this.$refs.memberRef.clearValidate();
      });
    },
    handleSizeChange() {
      console.log("handleSizeChange");
    },
    handleCurrentChange() {
      console.log("handleCurrentChange");
    },
    async getList() {
      let res = await getAllRole({
        ...this.paginationInfo,
        ...this.searchInfo,
      });
      if (res.code === 20041) {
        this.paginationInfo = res.data.page;
        this.tableData = res.data.rows;
        this.tableData.forEach((item) => {
          item.create_time = dayjs(item.create_time).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        });
      }
    },
    onOpen() {
      this.$nextTick(() => {
        this.$refs.addRef.clearValidate();
      });
    },
    showDialog(row) {
      this.showRow = row;
      this.memberVisible = true;
    },
  },
};
</script>
<style lang="less" scoped>
.RoleManagement {
  main {
    background-color: #fff;
    padding: 10px 20px;
    border-radius: 4px;
    .search-con {
      margin-bottom: 20px;
      .el-form-item {
        margin-bottom: 0;
      }
    }
    .table-con {
      .el-table {
        min-height: calc(100vh - 320px);
        margin-bottom: 10px;
      }
      & > .el-button {
        margin-bottom: 10px;
      }
    }
    .el-pagination {
      display: flex;
      justify-content: end;
    }
  }
}
</style>
<style lang="less">
.role-management-dialog {
  .dialog-content {
    display: flex;
    .left-content {
      padding-right: 20px;
      margin-right: 20px;
      border-right: 1px solid #e8eaed;
      .el-textarea .el-input__count {
        line-height: 16px;
      }
    }
    .right-content {
      flex: 1;
      .content-top {
        display: flex;
        justify-content: space-between;
        .el-input {
          max-width: 220px;
        }
      }
    }
  }
}
</style>
